package com.coolapk.controller;

import com.coolapk.entity.Favorite;
import com.coolapk.result.ResponseResult;
import com.coolapk.service.FavoriteService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.List;

import static com.coolapk.uitls.Upload.fileUpload;

@RestController
@RequestMapping("/user")
public class FavoriteController {

    @Resource
    FavoriteService favoriteService;

    @GetMapping("/getFavoriteList/{userId}")
    public ResponseResult getFavoriteList(@PathVariable Integer userId) {
        List<Favorite> favoriteList = favoriteService.selectFavoriteList(userId);
            return ResponseResult.success(1, "获取收藏列表成功",favoriteList);
    }

    @PostMapping("/saveFavorite")
    public ResponseResult saveFavorite(Favorite favorite){
        List<Favorite> favoriteList = favoriteService.selectFavoriteList(favorite.getUserId());
        for (Favorite f : favoriteList){
            if(favorite.getTitle().equals(f.getTitle())){
                return ResponseResult.failure(0,"收藏单标题已存在");
            }
        }
        String URL = fileUpload(favorite.getCoverFile());
        favorite.setCover(URL);
        Integer res = favoriteService.saveFavorite(favorite);
        if (res == 0){
          return ResponseResult.failure(-1,"新增收藏单失败");
        }else {
        return ResponseResult.success(1,"新增收藏单成功");
        }
    }

    @DeleteMapping("/deleteFavorite/{id}")
    public ResponseResult deleteFavorite(@PathVariable Integer id){
        Integer res = favoriteService.deleteFavorite(id);
        if (res == 0 ){
            return ResponseResult.failure(-1,"删除收藏单失败");
        }
        return ResponseResult.success(1,"删除收藏单成功");
    }
}
